package com.molichuxing.gateway.bff.basic.services.impl;

import java.time.LocalDateTime;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.molichuxing.gateway.bff.basic.convertor.Convert;
import com.molichuxing.gateway.bff.basic.entity.response.TerminalUpgradedVo;
import com.molichuxing.gateway.bff.basic.entity.response.VersionMobileVo;
import com.molichuxing.gateway.bff.basic.services.VersionBffService;
import com.molichuxing.services.business.service.VersionBizService;
import com.molichuxing.services.infrastructure.dto.request.create.DeviceCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.DeviceModifyDto;
import com.molichuxing.services.infrastructure.dto.response.DeviceDto;
import com.molichuxing.services.infrastructure.dto.response.VersionInfoDto;
import com.molichuxing.services.infrastructure.service.DeviceService;
import com.molichuxing.services.infrastructure.service.VersionInfoService;

@Service("versionBffService")
public class VersionBffServiceImpl implements VersionBffService {
    private static final Logger logger = LoggerFactory.getLogger(VersionBffServiceImpl.class);

    @Resource
    private VersionBizService versionBizService;

    @Resource
    private DeviceService deviceService;

    @Resource
    private VersionInfoService versionInfoService;


    @Value("${device_base_url}")
    private String DEVICE_BASE_URL;

    @Override
    public VersionMobileVo getNewestMobile(String appVersion, String channel) {
        return Convert.toVersionMobileVo(versionBizService.getNewestMobile(appVersion, channel));
    }

    /**
	 * 智能终端升级校验
	 * 
	 * @param appVersion
	 *            当前设备的app版本号
	 * @param cpuSerial
	 *            cpu号
	 * @param chaVersion
	 *            渠道版本号
	 * @param opVersion
	 *            操作系统版本号
	 * @return
	 */
    @Override
	public TerminalUpgradedVo findUpgradeInfo(String appVersion, String cpuSerial, String chaVersion,
			String opVersion) {
        TerminalUpgradedVo result = null;
        DeviceDto terminalInfo = deviceService.getDeviceByCpu(cpuSerial);
        //根据CPU号查询终端信息，如果没有录入一条
        if (terminalInfo == null){
            DeviceCreateDto newInfo = new DeviceCreateDto();
            newInfo.setCpu(cpuSerial);
			newInfo.setChannelVersionCode(chaVersion);
            newInfo.setOpVersion(opVersion);
            newInfo.setAppVersion(appVersion);
            deviceService.createDevice(newInfo);
            logger.info("录入一条该CPU对应的智能终端信息，CPU："+ cpuSerial);
        }else {
            //如果设备信息不一致，更新设备信息（app版本，渠道版本，操作系统）
            if(!(appVersion.equals(terminalInfo.getAppVersion())
                    && opVersion.equals(terminalInfo.getOpVersion())
					&& chaVersion.equals(terminalInfo.getChannelVersionCode()))) {
                DeviceModifyDto deviceModifyDto = new DeviceModifyDto();
                deviceModifyDto.setId(terminalInfo.getDeviceId());
                deviceModifyDto.setAppVersion(appVersion);
                deviceModifyDto.setOpVersion(opVersion);
				deviceModifyDto.setChannelVersionCode(chaVersion);
                deviceModifyDto.setGmtModified(LocalDateTime.now());
                //更新该终端信息
                deviceService.modifyDevice(deviceModifyDto);
            }
            //如果有升级信息
            if(terminalInfo.getVersionId()!=null && StringUtils.isNotBlank(terminalInfo.getTerminalVersionCode())){

                //判断终端版本号是否一致，不一致（特殊情况，返回false和msg）
                VersionInfoDto version = versionInfoService.getVersionById(terminalInfo.getVersionId());
                if (version == null){
                    logger.info("该CPU：【"+cpuSerial+"】的升级计划异常。");
                    throw new IllegalArgumentException("升级计划异常");

                }
                String terVersion = version.getTerminalVersionCode(); //升级版本对应的终端版本
                if(!terminalInfo.getTerminalVersionCode().equals(terVersion)){
                    logger.info("该CPU：【"+cpuSerial+"】的终端版本号异常。");
                    throw new IllegalArgumentException("升级版本与设备代数不符，请告知管理员重新发布版本！");

                }
                //如果app版本低于计划升级版本，推送升级信息（拼接的url,是否强制升级）
                int userApp = Integer.parseInt(appVersion.replace(".", "")); //当前智能终端版本
                int serApp = Integer.parseInt(versionInfoService.getVersionById(terminalInfo.getVersionId())
                        .getAppVersion().replace(".", "")); //计划升级版本

                if(userApp < serApp){
                    result = new TerminalUpgradedVo();
                    VersionInfoDto newVersion = versionInfoService.getVersionById(terminalInfo.getVersionId());
                    //url 拼接规则？？
                    String updateUrl = DEVICE_BASE_URL + newVersion.getAppVersion() +"_"+ newVersion.getChannelVersionCode()
                            +"_"+ newVersion.getTerminalVersionCode() +".apk";
                    result.setUpdateUrl(updateUrl);
                    result.setChannelVersion(newVersion.getChannelVersionCode());
                    result.setVersion(newVersion.getAppVersion());
                    result.setTitle(newVersion.getUpgradeTitle());
                    result.setDescription(newVersion.getUpgradeDescribe());
                    result.setIsUpgraded(newVersion.getIsUpgraded());

                }
            }
        }

        return result;
    }


}
